<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="zheng_tops">
        <n-button type="primary" @click="newContent"> 新建 </n-button>
        <n-button type="error" @click="deleContent" style="margin-left: 10px"> 批量删除 </n-button>
        <div class="searchs">
          <n-input
            placeholder="搜索用户ID"
            style="width: 270px; margin-left: 10px"
            v-model:value="inputValue"
          >
            <template #prefix>
              <n-icon :component="FlashOutline" />
            </template>
          </n-input>
          <n-button type="primary" @click="searchig" style="margin-left: 5px"> 搜索 </n-button>
        </div>
      </div>
      <div style="height: 20px"></div>
      <n-data-table
        striped
        :columns="columns"
        :data="allData"
        :pagination="pagination"
        :row-key="rowKey"
        :align="right"
        :scroll-x="1500"
        @update:checked-row-keys="handleCheck"
      />
    </n-card>
    <!-- 编辑 -->
    <n-modal
      v-model:show="showModals"
      :mask-closable="false"
      :on-after-leave="modelClose"
      preset="dialog"
      title="编辑"
    >
      <div>
        <n-form
          ref="formRef"
          :model="tableDate"
          :rules="rules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-form-item label="姓名" path="rname">
            <n-input v-model:value="tableDate.rname" placeholder="请输入姓名" />
          </n-form-item>
          <n-form-item label="账号" path="account">
            <n-input v-model:value="tableDate.account" placeholder="请输入账号" readonly />
          </n-form-item>
          <n-form-item label="密码" path="passworld">
            <n-input v-model:value="tableDate.passworld" placeholder="请输入密码" />
          </n-form-item>
          <div style="display: flex; justify-content: flex-end">
            <n-button round type="primary" @click="handleValidateButtonClick"> 保存 </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
    <!-- 新建 -->
    <n-modal v-model:show="showNew" :mask-closable="false" preset="dialog" title="新建">
      <div>
        <n-form
          ref="formRefs"
          :model="newModel"
          :rules="newRules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-form-item label="角色" path="type">
            <n-select
              v-model:value="newModel.type"
              placeholder="请选择等级"
              :options="generalOptions"
            />
          </n-form-item>
          <n-form-item label="企业" path="id">
            <n-select
              v-model:value="newModel.id"
              placeholder="请选择"
              :options="qId"
              @change="qidChange"
            />
          </n-form-item>
          <n-form-item label="项目" path="qid">
            <n-select v-model:value="newModel.qid" placeholder="请选择" :options="xiangIds" />
          </n-form-item>
          <n-form-item label="姓名" path="name">
            <n-input v-model:value="newModel.name" placeholder="请输入姓名" />
          </n-form-item>
          <n-form-item label="账号" path="account">
            <n-input v-model:value="newModel.account" placeholder="请输入账号" />
          </n-form-item>
          <n-form-item label="密码" path="passworld">
            <n-input v-model:value="newModel.passworld" placeholder="请输入密码" />
          </n-form-item>
          <div style="display: flex; justify-content: flex-end">
            <n-button round type="primary" @click="handleValidateButtonClicks"> 确认 </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
  </div>
</template>
<script>
  import { h, ref, defineComponent, getCurrentInstance, reactive } from 'vue';
  import { useMessage, NButton, useDialog } from 'naive-ui';
  import { FlashOutline } from '@vicons/ionicons5';

  const createColumns = ({ play, dele }) => {
    return [
      {
        type: 'selection',
      },
      {
        title: '账户ID',
        key: 'id',
        width: 50,
      },
      {
        title: '角色ID',
        key: 'type',
        width: 80,
      },
      {
        title: '姓名',
        key: 'name',
        width: 80,
      },
      {
        title: '角色名称',
        key: 'rname',
        width: 120,
      },
      {
        title: '账号',
        key: 'account',
        width: 130,
      },
      {
        title: '项目ID',
        key: 'project_id',
        width: 80,
      },
      {
        title: '项目名称',
        key: 'pname',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'create_time',
        width: 120,
      },
      {
        title: '操作',
        fixed: 'right',
        width: 70,
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'info',
              onClick: () => play(row),
            },
            { default: () => '编辑' }
          );
        },
      },
      {
        key: 'actions',
        width: 70,
        fixed: 'right',
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => dele(row),
            },
            { default: () => '删除' }
          );
        },
      },
    ];
  };

  export default defineComponent({
    setup() {
      const allData = ref();
      const message = useMessage();
      const showModals = ref(false);
      const showNew = ref(false);
      const showModalRef = ref(false);
      const checkedRowKeysRef = ref([]);
      const formRef = ref(null);
      const formRefs = ref(null);
      const tableDate = ref({});
      const dialog = useDialog();
      const inputValue = ref('');
      const generalOptions = ref([]);
      const qId = ref([]);
      const xiangId = ref([]);
      const checkKeys = reactive({
        checkKey: [],
      });
      const newModel = reactive({
        type: null,
        name: '',
        id: null,
        qid: null,
        account: '',
        project_id: '',
        passworld: '',
      });

      let { proxy } = getCurrentInstance();
      const lists = () => {
        proxy
          .$axios({
            url: '/api/role/user/index', //列表数据
            method: 'post',
            data: {
              admin_id: 1,
              admin_name: '张三',
            },
          })
          .then((res) => {
            console.log(res.data.data);
            allData.value = res.data.data.list;
            for (let i = 0; i < res.data.data.list.length; i++) {
              const obj = {};
              obj.label = res.data.data.list[i].name;
              obj.value = res.data.data.list[i].id;
              generalOptions.value.push(obj);
            }
            for (let i = 0; i < res.data.data.firm.length; i++) {
              const qobj = {};
              qobj.label = res.data.data.firm[i].name;
              qobj.value = res.data.data.firm[i].id;
              qId.value.push(qobj);
            }
            for (let i = 0; i < res.data.data.info.length; i++) {
              const xobj = {};
              xobj.label = res.data.data.info[i].name;
              xobj.value = res.data.data.info[i].id;
              xobj.index = res.data.data.info[i].qid;
              xiangId.value.push(xobj);
            }
          });
      };
      lists();

      //角色列表接口
      proxy
        .$axios({
          url: '/api/role/role/index',
          method: 'post',
          data: {
            admin_id: 1,
            admin_name: '张三',
          },
        })
        .then((res) => {
          console.log(res.data.data.list);
          for (let i = 0; i < res.data.data.list.length; i++) {
            const obj = {};
            obj.label = res.data.data.list[i].name;
            obj.value = res.data.data.list[i].id;
            generalOptions.value.push(obj);
          }
          console.log(generalOptions.value);
        });
      //点击新建
      const newContent = () => {
        showNew.value = true;
      };
      //批量删除
      const deleContent = () => {
        proxy
          .$axios({
            url: '/api/certificate/index/del',
            method: 'post',
            data: {
              id: checkKeys.checkKey.join(','),
              admin_id: 111,
              admin_name: '张',
            },
          })
          .then((res) => {
            console.log(res.data);
            if (res.code == 1) {
              message.success('删除成功');
              lists();
            }
          });
      };
      //搜索
      const searchig = () => {
        console.log(inputValue.value);
        proxy
          .$axios({
            url: '/api/certificate/index/user_certificate',
            method: 'post',
            data: {
              uid: inputValue.value,
              admin_id: 111,
              admin_name: '张',
            },
          })
          .then((res) => {
            console.log(res.data);
            allData.value = res.data;
          });
      };
      // 转时间戳
      const timestampToTime = (timestamp) => {
        let datesd = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = datesd.getFullYear() + '-';
        let M =
          (datesd.getMonth() + 1 < 10 ? '0' + (datesd.getMonth() + 1) : datesd.getMonth() + 1) +
          '-';
        let D = datesd.getDate() < 10 ? '0' + datesd.getDate() : datesd.getDate();
        return Y + M + D;
      };
      // 项目ID企业ID联动选择
      const xiangIds = ref([]);
      const qidChange = (e) => {
        console.log(e);
        console.log(qId.value[e - 1].value);
        xiangIds.value = xiangId.value.filter((item) => {
          return item.index === qId.value[e - 1].value;
        });
      };
      /////////
      const paginationReactive = reactive({
        page: 1,
        pageSize: 5,
        showSizePicker: true,
        pageSizes: [3, 5, 7],
        onChange: (page) => {
          paginationReactive.page = page;
        },
        onUpdatePageSize: (pageSize) => {
          paginationReactive.pageSize = pageSize;
          paginationReactive.page = 1;
        },
      });
      return {
        allData,
        FlashOutline,
        newContent,
        showNew,
        formRef,
        formRefs,
        tableDate,
        searchig,
        inputValue,
        checkKeys,
        deleContent,
        timestampToTime,
        generalOptions,
        qId,
        xiangId,
        qidChange,
        xiangIds,
        columns: createColumns({
          play(row) {
            console.log(row);
            tableDate.value = row;
            showModals.value = true;
          },
          dele(row) {
            console.log(row.id);
            dialog.warning({
              title: '删除',
              content: '你确定要删除吗？',
              positiveText: '确定',
              negativeText: '不确定',
              onPositiveClick: () => {
                proxy
                  .$axios({
                    url: '/api/role/user/del',
                    method: 'post',
                    data: {
                      id: row.id,
                      admin_id: 11,
                      admin_name: '张',
                    },
                  })
                  .then((res) => {
                    console.log(res.data);
                    if (res.code == 1) {
                      message.success('删除成功');
                      lists();
                    }
                  });
              },
              onNegativeClick: () => {},
            });
          },
        }),
        checkedRowKeys: checkedRowKeysRef,
        pagination: paginationReactive,
        rowKey: (row) => row.id,
        handleCheck(rowKeys) {
          checkKeys.checkKey = rowKeys;
          console.log(checkKeys.checkKey.join(','));
        },
        // 编辑弹窗
        showModals,
        showModal: showModalRef,
        // 弹窗表单
        model: ref({
          name: null,
          level: null,
          number: null,
          time: null,
          times: null,
        }),
        newModel,
        rules: {
          name: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          account: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          passworld: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
        },
        newRules: {
          // type: {
          //   required: true,
          //   trigger: ['blur', 'change'],
          //   message: '请选择内容',
          // },
          // id: {
          //   required: true,
          //   trigger: ['blur', 'change'],
          //   message: '请输入内容',
          // },
          // name: {
          //   required: true,
          //   trigger: ['blur', 'input'],
          //   message: '请输入内容',
          // },
          // account: {
          //   required: true,
          //   trigger: ['blur', 'input'],
          //   message: '请输入内容',
          // },
          // passworld: {
          //   required: true,
          //   trigger: ['blur', 'input'],
          //   message: '请输入内容',
          // },
        },
        //确认编辑
        handleValidateButtonClick(e) {
          e.preventDefault();
          console.log(tableDate.value.id);
          console.log(tableDate.value.type);
          console.log(tableDate.value.name);
          console.log(tableDate.value.account);
          console.log(tableDate.value.passworld);
          console.log(tableDate.value.project_id);

          formRef.value?.validate((errors) => {
            if (!errors) {
              proxy
                .$axios({
                  url: '/api/role/user/edit',
                  method: 'post',
                  data: {
                    id: tableDate.value.id,
                    type: tableDate.value.type,
                    uid: tableDate.value.uid,
                    name: tableDate.value.name,
                    account: tableDate.value.account,
                    passworld: tableDate.value.passworld,
                    project_id: tableDate.value.project_id,
                    admin_id: 1,
                    admin_name: '张',
                  },
                })
                .then((res) => {
                  console.log(res.data);
                  if (res.data.code == 1) {
                    message.success('编辑成功');
                    lists();
                    showModals.value = false;
                  }
                });
            } else {
              console.log(errors);
              message.error('编辑失败');
            }
          });
        },
        handleValidateButtonClicks(e) {
          console.log(newModel.name);
          console.log(newModel.passworld);
          console.log(newModel.account);
          console.log(newModel.type);
          console.log(newModel.id);
          console.log(newModel.qid);
          e.preventDefault();
          formRefs.value?.validate((errors) => {
            if (!errors) {
              proxy
                .$axios({
                  url: '/api/role/user/add',
                  method: 'post',
                  data: {
                    name: newModel.name,
                    type: newModel.type,
                    account: newModel.account,
                    passworld: newModel.passworld,
                    project_id: newModel.qid,
                    qyid: newModel.id,
                    admin_id: 1,
                    admin_name: '张三',
                  },
                })
                .then((res) => {
                  console.log(res);
                  if (res.data.code == 1) {
                    message.success('添加成功');
                    showNew.value = false;
                    newModel.name = '';
                    newModel.type = '';
                    newModel.account = '';
                    newModel.passworld = '';
                    newModel.id = null;
                    newModel.qid = null;
                    lists();
                  }
                });
            } else {
              console.log(errors);
              message.error('添加失败');
            }
          });
        },
      };
    },
  });
</script>
<style scoped>
  .win_input {
    width: 100%;
    padding: 5px;
  }
  .win_input label {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 5%;
  }
  .win_input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    border: 1px solid rgb(189, 187, 187);
    border-radius: 5px;
    outline-color: #8ebbee;
  }
  .win_input input:focus {
    box-shadow: 1px 1px 3px #4098fc;
    border: none;
  }
  .win_input input:hover {
    border: 1px solid #4098fc;
  }
  .win_input p {
    width: 60px;
    text-align: end;
  }
  .zheng_tops {
    width: 100%;
    display: flex;
  }
  .searchs {
    width: 27%;
    display: flex;
    justify-content: space-around;
  }
</style>
